//用户登陆
function checkLogin(){
    var account = $("#username").val();
    var psd =$.md5($("#password").val());
    $.ajax({
        type: "POST",
        url: "http://47.98.125.66/loginuser",
        dataType: "JSON",
        data: {
            account:account,
            psd:psd
        },
        success: function(result) {
        
          if(result){
            var staffId = result.staffId;
            var token = result.token;
            localStorage.setItem("staffId",staffId);
            localStorage.setItem("token",token);

            window.location.href = "../../project/index/index.html";
          } 
        
        },
        error: function() {
             $("#mymodal").modal();
        }
    });

      localStorage.setItem("account",account);
}
    var staffId = localStorage.getItem("staffId");
    var token = localStorage.getItem("token");

//模态弹出框垂直居中
$('#mymodal').on('shown.bs.modal', function (e) {
    $(this).css('display', 'block');
    var modalHeight=$(window).height() / 2 - $('#mymodal .modal-dialog').height() / 2;
    $(this).find('.modal-dialog').css({
    'margin-top': modalHeight
    });
});


//模态弹出框关闭
$("button,#close").on('click',function(){
    $("#mymodal").modal("hide");
});

//员工基本信息展示
function StaffInformation(){
     
    var staffId = localStorage.getItem("staffId");
    var token = localStorage.getItem("token");
    $.ajax({
        type: "GET",
        url: "http://47.98.125.66/StaffInformation/" + staffId +"/" +token,
        dataType: "JSON",
        success: function(result) {
          if(result){
             console.log(result);
            var name = result.name;
            var department = result.department;
             if(result.dream == null) {
                 $(".dream1").text("暂未填写");
            } else {
                 localStorage.setItem("ADream",result.dream);
                 var dreamList = result.dream.split("&%");
                 $(".dream1").text(dreamList[0]);
                 $(".dream2").text(dreamList[1]);
                 $(".dream3").text(dreamList[2]);
            }
            
            $(".name").text(name);
            $(".department").text(department);
           
          } 
        
        },
        error: function() {
            console.log("连接错误");
        }
    });
}
 
//首页各个模块页面跳转
var a=$("#a") , b=$("#b") , c=$("#c") , d=$("#d");
a.on('click', function() {
    window.location.href = "./../mine/mine.html";
});
b.on('click', function() {
    window.location.href = "./../cash/cash.html";
});
c.on('click', function() {
    window.location.href = "./../feedback/feedback.html";
});
d.on('click', function() {
    window.location.href = "./../modification/modification.html";
});

//我的梦想基金显示
function Mydreamfund() {
    $.ajax({
        type: "GET",
        url: "http://47.98.125.66/myfund/" + staffId +"/" +token,
        dataType: "JSON",
        success: function(result) {
          if(result){
            console.log(result);
            for(var i=0; i<result.length; i++){
               var balance = result[i].balance;
               var drawTotal = result[i].drawTotal;
              var yearList = result[i].year;

               localStorage.setItem("balance",balance);

               $(".balance").text(balance+"元");
               $(".drawTotal").text(drawTotal+"元"); 

               if(yearList == null) {
                $(".showfundList").append(
                 "<div class='sublist row'>"+
                "<div class='list-font col-xs-12'>" +
                "暂无梦想基金明细信息" + "</div>"+ "</div>");
                } else {
                    var yearArr = yearList.replace("[","").replace("]","").split(",");
                    localStorage.setItem("yearArr",yearArr);
                    for(var i=0; i<yearArr.length; i++){
                        $(".showfundList").append(
                 "<li class='e sublist row'>"+
                "<div class='todetail list-font col-xs-10'>" + yearArr[i]
                +"年基金梦想基金明细" + "</div>"+
                "<div  class='glyphicon glyphicon-chevron-right col-xs-2' >"+
                "</div>" + "</li>");
               
                    }
                }
            }
            toPaymentDetail();

          } 
        
        },
        error: function() {
             console.log("连接错误");
        }
    });
}

//跳转至收支明细
function toPaymentDetail(){
  var yearArr = localStorage.getItem("yearArr");
  var PerYear = yearArr.split(",");
  console.log(typeof PerYear);
  var list = document.getElementsByTagName('li');
  for(var i=0; i<list.length; i++){
     list[i].addEventListener('click', function(i) {
       return  function(){
                  var year = PerYear[i];
                  localStorage.setItem("year",year); 
                  console.log(yearArr[i]);
                  window.location.href = "./../mine/mine-detail.html";
                }                                        
     }(i),true);
   }
}

//显示收支明细信息
function showDetail(){
    var Year = localStorage.getItem("year");
     console.log("要查询的年份:"+Year);
    $.ajax({
        type: "GET",
        url: "http://47.98.125.66/paymentdetail/" + staffId +"/"+Year+"/" +token,
        dataType: "JSON",
        success: function(result) {
          if(result){
             console.log(result);
              var balance = result[0].balance;
              var applyNum = result[0].applyNum;
              var money = result[0].money;
              var year = result[0].year;
              var mincrement =result[0].mincrement;
              var lastyear = result[0].lastyear;
              var createtime = result[0].createtime;
              var createTime = result[0].createTime;

              if(createTime == null){
                 createTime="";
              }
            
              $(".js-showYear").text(year+"年");
              $(".js-lastyear").text(lastyear+"年");

              $(".js-balance").text(balance);
              $(".js-applyNum").text(applyNum);
              $(".js-money").text(money);
              $(".js-mincrement").text(mincrement);
              
              var total1 = balance + mincrement+money-applyNum;
               $(".js-total1").text(total1);
               var total2 = balance + mincrement+money;
               $(".js-total2").text(total2);
              var total3 = mincrement+balance;
               $(".js-total3").text(total3);
              
              

              var syMoney = money + mincrement;
               $(".js-syMoney").text(syMoney);

                $(".js-tixian").text(createTime);
                $(".js-time").text(createtime);


          } 
        
        },
        error: function() {
            console.log("连接错误");
        }
    });
}

//申请提现页面跳转
var cashMoney=$("#cashMoney") , cashDream=$("#cashDream");  
cashDream.on('click', function() {
    window.location.href = "./../cash/cash-dream.html";
});


//修改资料页面跳转修改秘密
var modifyPsd = $("#modifyPsd");
modifyPsd.on('click', function() {
    window.location.href = "./../modification/modification-password.html";
});

//判断梦想是否填满
function isfullDream() {

  $.ajax({
        type: "POST",
        url: "http://47.98.125.66/isfulldream/",
        dataType: "JSON",
         data:{
            staffId:staffId
        },
        
        success: function(result) {
           if(result.code==0){
            //不可填写梦想 disabled  readOnly（可以发送到后台）
             $(".Tdream1").attr("readOnly",true); 
             $(".Tdream2").attr("readOnly",true); 
             $(".Tdream3").attr("readOnly",true); 
             $(".postDream").attr("readOnly",true);
             $(".tips").text("(今年，你的梦想不可以修改了)");
           }
           else if(result.code==1) {
            //可以填写一个梦想
             $(".Tdream2").attr("readOnly",true); 
             $(".Tdream3").attr("readOnly",true);
             $(".tips").text("(今年，你还可以填写/修改一个梦想)");
             
           }
           else if(result.code==2) {
            //可以填写两个梦想
             $(".Tdream3").attr("readOnly",true);
             $(".tips").text("(今年，你还可以填写/修改两个梦想)");
           }
           else if(result.code==3){
            //可以填写三个梦想
            $(".tips").text("(今年，你可以填写/修改三个梦想)");
           }           
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                      alert("出错啦！");
       }
    });

}
function showAdream() {
               var ADream = localStorage.getItem("ADream");
                 var dreamList = ADream.split("&%");
                 $(".Tdream3").text(dreamList[0]);
                 $(".Tdream2").text(dreamList[1]);
                 $(".Tdream1").text(dreamList[2]);
}
//修改资料提交梦想
function TdreamA(Tdream){
  var staffId1 = parseInt(staffId);
  var createTime = Date.parse(new Date()) ;
  var updateTime = Date.parse(new Date()); 
  $.ajax({
        type: "POST",
        contentType:'application/json',
        url: "http://47.98.125.66/dreampost/",
        dataType: "JSON",
         data: JSON.stringify({
            "staffId":staffId1 ,
            "dream":Tdream,
            "createTime":createTime,
            "updateTime":updateTime,
            "token" :token
        }),
        success: function(result) {
          if(result.status==0){
            alert("今年已修改过梦想，请勿再次修改！" );
            } else {
              alert("梦想修改成功！");
              setTimeout(function(){
              window.location.href = "./../index/index.html";
            }, 500);
            }
        },
         error: function(XMLHttpRequest, textStatus, errorThrown) {
                           alert("提交失败！");
                        
       }
    });
}
function TdreamPost(){
    var Tdream1 = $(".Tdream1").val();
    var Tdream2 = $(".Tdream2").val();
    var Tdream3 = $(".Tdream3").val();
    if(Tdream1.length==0 && Tdream2.length==0 && Tdream3.length==0){
      alert("请填写梦想");
    } else if(Tdream1.length>0 && Tdream2.length==0 && Tdream3.length==0){
      var Tdream = Tdream1;
      TdreamA(Tdream);
    } else if (Tdream1.length==0 && Tdream2.length>0 && Tdream3.length==0){
      var Tdream = Tdream2;
      TdreamA(Tdream);
    } else if (Tdream1.length==0 && Tdream2.length==0 && Tdream3.length>0){
      var Tdream = Tdream3;
      TdreamA(Tdream);
    } else if(Tdream1.length>0 && Tdream2.length>0 && Tdream3.length==0){
      var Tdream = (Tdream1 +'&%' + Tdream2);
      TdreamA(Tdream);
    } else if (Tdream1.length>0 && Tdream2.length==0 && Tdream3.length>0){
      var Tdream = (Tdream1 +'&%' + Tdream3);
      TdreamA(Tdream);
    } else if (Tdream1.length==0 && Tdream2.length>0 && Tdream3.length>0){
      var Tdream = (Tdream2 +'&%' + Tdream3);
      TdreamA(Tdream);
    } else if(Tdream1.length>0 && Tdream2.length>0 && Tdream3.length>0){
      var Tdream = Tdream1 + '&%' + Tdream2 + '&%' + Tdream3;
      TdreamA(Tdream);
    }
}


//提交留言,问题反馈
function QuestionPost(){
    var staffId1 = parseInt(staffId); 
    var problem  = $("#problem").val();
    var email = $("#email").val();
    var problemType = $('input[name="identity"]:checked ').val();

    var createTime = Date.parse(new Date()) ;
    var updateTime = Date.parse(new Date());

    var myReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
 

    if(email.length == 0 || problem.length == 0){
      alert("请填写邮箱和问题");
    } 
    else if(!myReg.test(email)){
　　　　 $("#email").val("");
         $(".emailtip").text("邮箱格式不对!");
      } else {

        $.ajax({
        type: "POST",
        contentType:'application/json',
        url: "http://47.98.125.66/problempost/",
        dataType: "JSON",
         data: JSON.stringify({
            "staffId":staffId1 ,
            "problem":problem,
            "problemType":problemType,
            "email":email,
            "status":0,
            "createTime":createTime,
            "updateTime":updateTime,
            "token" :token
        }),
        
        success: function(result) {
            alert("提交成功" );
            setTimeout(function(){
              window.location.href = "./../index/index.html";
            }, 500);
          
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if(XMLHttpRequest.status==200&&XMLHttpRequest.readyState==4){
                          alert("提交成功！");
                        } else {
                           alert("提交失败！");
                        }
       }
    });
  }
}

//申请提现状态
function TapplicationStatus() {
    $.ajax({
        type: "POST",
        url: "http://47.98.125.66/application/status/",
        dataType: "JSON",
         data: {
            staffId:staffId,
         },
        success: function(result) {

          console.log(result);
          var allNum = result.allNum;
          var bestNum = result.bestNum;
          localStorage.setItem("allNum",allNum);
          localStorage.setItem("bestNum",bestNum);
            console.log(result.status);
            if(result.status==0) {
              $(".status-tips").text("（上一次提现审核失败，您当前可以进行提现！）");
              cashMoney.on('click', function() {
              window.location.href = "./../cash/cash-money.html";
        });
            } 
            else if(result.status==1) {
               $(".list-font").addClass("status-font");
               $(".status-tips").text("（上一次提现审核已成功!）");
            }
             else if(result.status==2) {
              $(".list-font").addClass("status-font");
               $(".status-tips").text("（上一次提现审核进行中!）");
            }
             else if(result.status==3) {
               $(".status-tips").text("（您当前可以进行提现！）");
              cashMoney.on('click', function() {
                  window.location.href = "./../cash/cash-money.html";
        });
            }
            else if(result.status==4) {
               $(".list-font").addClass("status-font");
               $(".status-tips").text("（第一次分配的基金未存满一年！）");
            } else if(result.status==5){
              $(".list-font").addClass("status-font");
              $(".status-tips").text("（您还未分配到基金！）");
            }
          
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                        
         alert("出错啦！");
                        
       }
    });

}


//提现
function TapplicationGet(){
   var bestNum = parseFloat(localStorage.getItem("bestNum"));
   var staffId1 =  parseInt(staffId); 
   var applyNum = parseFloat($(".applyNum").val());

   var createTime = Date.parse(new Date()).toString();
   var updateTime = Date.parse(new Date()).toString();
   var manageTime = Date.parse(new Date()).toString();
   var date=new Date;
   var Year=date.getFullYear().toString(); 
    if(bestNum == 0 ){
      $(".applytip").text("可申请金额0元");
    } 
    else if(isNaN(applyNum)){
     $(".applytip").text("请填写申请金额");
   }
    else if(applyNum > bestNum){
     $(".applyNum").val("");
     $(".applytip").text("申请金额超出可提现范围");
   } else {

     $.ajax({
        type: "POST",
        dataType: "JSON",
        contentType:"application/json",
        url: "http://47.98.125.66/application/applyNum",
        
         data: JSON.stringify({
            "staffId":staffId1,
            "applyNum":applyNum,
            "applyType":0,
            "applyYear":Year,
            "createtime":createTime,
            "status":2,
            "picUrl":null,
            "managetime":manageTime,
            "updatetime":updateTime,
            "remark":null,
            "token" :token
        }),
        success: function(result) {
            alert("提交成功!等待审核" ); 
            setTimeout(function(){
              window.location.href = "./../index/index.html";
            }, 500);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if(XMLHttpRequest.status==200&&XMLHttpRequest.readyState==4){
                          alert("提交成功!等待审核");
                        } else {
                           alert("提交失败！");
                        }
       }
    });
  }
}

//提现页面展示余额
function showBalance() {

  var allNum = localStorage.getItem("allNum");
  var bestNum = localStorage.getItem("bestNum");
  $(".showAllNum").text(allNum+"元");
  $(".showBestNum").text(bestNum);

}

//记住我
// function remember(){
//      var staffId = localStorage.getItem("account");
//      $("#username").val(account);
// }


//梦想兑现页面图片上传功能
 function  viewimg($event) {
       //获取当前的input标签 
       var currentObj = event.currentTarget; 
      //找到要预览的图片img标签，亦可动态生成 
       var img = currentObj.parentNode.children[0]; 
      setImagePreview(currentObj, img); 
      function setImagePreview(docObj, imgObjPreview) {
        if (docObj.files && docObj.files[0]) {
        imgObjPreview.style.display = 'block'; 
        imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]); 
      } 
    }
 }
  function image(){
   var staffId1 = parseInt(staffId); 
   var allNum = localStorage.getItem("allNum");

   var createTime = Date.parse(new Date()).toString();
   var updateTime = Date.parse(new Date()).toString();
   var manageTime = Date.parse(new Date()).toString();
   var date=new Date;
   var Year=date.getFullYear().toString(); 

     //单张图片上传 
     var inputs = $("input.fileupload"); 
     for (var i = 0; i < inputs.length; i++) { 
     //图片转base64上传 
     var file = inputs[i].files;
     if(file[0]==undefined){
      alert("文件未上传！")
     } 
     if (file[0]) { 
      var reader = new FileReader(); 
      reader.readAsDataURL(file[0]); 
      reader.onload = function(e) {
          var event = this; 
          console.log(typeof event.result);
          $.ajax({ 
          type: "POST",
          contentType:'application/json',
          url: "http://47.98.125.66/application/applyNum",
          dataType: "JSON", 
          data: JSON.stringify({
            "staffId":staffId1,
            "applyNum":allNum,
            "applyType":1,
            "applyYear": Year,
            "createtime":createTime,
            "status":2,
            "picUrl":event.result,
            "managetime":manageTime,
            "updatetime":updateTime,
            "remark":null,
            "token" :token
        }),
          success: function(data) { 
              alert("提交成功!等待审核");
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if(XMLHttpRequest.status==200&&XMLHttpRequest.readyState==4){
                         alert("提交成功!等待审核");
                      } else {
                        alert("提交失败！");
               }
            }
          });
        } 
     } 
  } 
}


function back(){
   window.location.href = "./../index/index.html";
}

function toLogin(){
   localStorage.removeItem("token");
  window.location.href = "./../index/login.html";
}

function backToMine(){
  window.location.href = "./../mine/mine.html";
}
 function hasToken() {
  if( token == undefined){
   window.location.href = "./../index/login.html";
  }
 }



//判断ios，如果是ios就去掉capture属性.
function IosAnd() {
        // var file = document.querySelector('input');
        // if (getIos()) {
        //     file.removeAttribute("capture");
        // }
        // function getIos() {
        //     var ua=navigator.userAgent.toLowerCase();
        //     if (ua.match(/iPhone\sOS/i) == "iphone os") {
        //         return true;
        //     } else {
        //         return false;
        //     }
        // }

         //解决上传图片时capture="camera"在安卓与IOS的兼容性问题（在IOS只能拍照，不能选相册）
    var ua = navigator.userAgent.toLowerCase();//获取浏览器的userAgent,并转化为小写——注：userAgent是用户可以修改的
    var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);//判断是否是苹果手机，是则是true
    if (isIos) {
       $("input:file").removeAttr("capture");
    };
}


//修改密码$.trim()
function changepsd(){
  var Opsd = $.trim($("#Opsd").val());
  console.log(typeof Opsd);
  var Npsd = $("#Npsd").val();
  var npsd = $("#npsd").val();

  if(Opsd=='' || Npsd=='' || npsd==''){
     $(".psdDiff").text("请填写完整！");
  }
  else if(Npsd != npsd){
    $(".psdDiff").text("两次输入密码不一致！");
  }
  else if(Npsd == Opsd && Opsd == npsd){
    $(".psdDiff").text("新密码与旧密码相同，请重新修改！");
  }
   else {
   $(".psdDiff").text("");
   $.ajax({ 
          type: "POST",
          url: "http://47.98.125.66/changepsd",
          dataType: "JSON", 
          data: {
             staffId:staffId,
             Opsd:Opsd,
             Npsd:Npsd
        },
          success: function(data) { 
              if(data.code==1){
                alert("密码修改成功！请重新登录");
                setTimeout(function(){
                   window.location.href = "./../index/login.html";
            }, 500);
              }
               if(data.code==0){
                $(".psdDiff").text("原密码填写错误！");
              }
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
                    
               alert("出错啦！");
            }
          });
 }
}

function toLogin2() {
    window.location.href = "project/index/login.html";
}